# coding=utf-8
import json

from common import orm
from common.channel.model import Channel
from common.utils import track_logging
from common.utils.db import list_object, get, upsert, delete
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)


@sql_wrapper
def get_channels_in_ids(chn_ids):
    if not chn_ids:
        return []
    chns = Channel.query.filter(Channel.id.in_(chn_ids)).all()
    return chns


@sql_wrapper
def get_channel(id):
    return get(Channel, id)


@sql_wrapper
def upsert_channel(info, id=None):
    return upsert(Channel, info, id)


@sql_wrapper
def list_channel(query_dct):
    return list_object(query_dct, Channel)


@sql_wrapper
def delete_channel(id):
    delete(Channel, id)


@sql_wrapper
def modify_channel_info(info, id):
    item = Channel.query.filter(Channel.id == id).first()
    if item is None:
        return
    j = json.loads(item.info)
    if j.get('incr_risk', None) is None:
        j['incr_risk'] = {}
    flag = False
    for k, v in info.iteritems():
        if k in ["min_amount", "max_amount"]:
            j[k] = v
            flag = True
        if k in ["daily_start", "daily_end"]:
            kk = k.split('_')[1]
            if j.get('daily_open_time', None) is None:
                j['daily_open_time'] = {}
            j['daily_open_time'][kk] = v
            flag = True
        if k in ["daily_amount", "daily_count"]:
            kk = k.split('_')[1]
            if j['incr_risk'].get('daily', None) is None:
                j['incr_risk']['daily'] = {}
            j['incr_risk']['daily'][kk] = v
            flag = True
        if k in ["hourly_amount", "hourly_count"]:
            kk = k.split('_')[1]
            if j['incr_risk'].get('hourly', None) is None:
                j['incr_risk']['hourly'] = {}
            j['incr_risk']['hourly'][kk] = v
            flag = True
        if k in ["minutely_amount", "minutely_count"]:
            kk = k.split('_')[1]
            if j['incr_risk'].get('minutely', None) is None:
                j['incr_risk']['minutely'] = {}
            j['incr_risk']['minutely'][kk] = v
            flag = True
    if flag:
        item.info = json.dumps(j, sort_keys=True, separators=(',', ':'))
        item.save()


@sql_wrapper
def modify_channels_ip_white_lists_according_chn_type(id):
    item = Channel.query.filter(Channel.id == id).first()
    Channel.query.filter(Channel.chn_type == item.chn_type).update({"ip_white_list": item.ip_white_list})
    orm.session.commit()


@sql_wrapper
def make_channel_test(channel_id, mch_id):
    item = Channel.query.filter(Channel.id == channel_id).first()
    if item is None:
        return
    c = Channel()
    c.name = u'[测试]' + item.name
    c.service_name = 'test'
    c.chn_type = item.chn_type
    c.mch_id = mch_id
    c.weight = item.weight
    c.levels = item.levels
    c.open_type = item.open_type
    c.info = item.info
    c.status = 1
    c.rate = item.rate
    c.ip_white_list = item.ip_white_list
    c.save()
    return c


@sql_wrapper
def set_channel_test(channel_id, test_id):
    item = Channel.query.filter(Channel.id == channel_id).first()
    if item is None:
        return
    item_test = Channel.query.filter(Channel.id == test_id).filter(Channel.service_name == 'test').first()
    if item_test is None:
        return
    item_test.name = u'[测试]' + item.name
    item_test.chn_type = item.chn_type
    item_test.mch_id = item.mch_id
    item_test.weight = item.weight
    item_test.levels = item.levels
    item_test.open_type = item.open_type
    item_test.info = item.info
    item_test.status = 1
    item_test.save()
